from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from orders.models import OrderInfo
from pay.models import Payment

'''
１　 GET/orders/(?P<order_id>\d+)/payment/　请求方式
２　当前端将id 传过来　我们进行商品订单的查询订单信息
３　创建支付宝实例
４　生成order_string
５　拼接支付url

'''
from rest_framework.permissions import IsAuthenticated


class PaymentAPIview(APIView):
    permission_classes = [IsAuthenticated]

    def get(self,request,order_id):

        try:
            order = OrderInfo.objects.get(order_id = order_id,
                                          user = request.user,
                                          status = OrderInfo.ORDER_STATUS_ENUM['UNPAID'])

        except OrderInfo.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 创建支付宝实例
        from alipay import AliPay
        from mall import settings
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            # 默认回调url
            app_notify_url=None,
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            # RSA 或者 RSA2
            sign_type="RSA2",
            # 默认False
            debug=settings.ALIPAY_DEBUG
        )

        subject = '测试订单'
        # 4.生成order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),  # 货比类型要转换为str order.total_amount
            subject=subject,
            return_url="http://www.meiduo.site:8080/pay_success.html"
        )

        # 5.拼接支付的url
        alipay_url = settings.ALIPAY_URL + '?' + order_string

        return Response({'alipay_url': alipay_url})



'''
PUT /pay/status/? 支付宝参数
１　接受参数　更新操作
２　根据支付宝文档进行数据验证
３　如果验证成功则获取支付宝订单号和流水号
４　将流水号和订单保存起来　、
５　更新订单状态

'''


class PayStatusAPIview(APIView):
    permission_classes = [IsAuthenticated]

    def put(self,request):
        # 接收查询的字符串 将字符串转换成字典
        data = request.query_params.dict()
        # 根据支付宝文档进行验证 sign 不能进行签名验证
        signature = data.pop('sign')
        # verify
        from alipay import AliPay
        from mall import settings
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )
        success = alipay.verify(data, signature)

        if success:

            # 第一个是支付宝流水号　第二个是订单号
            trade = data.get('trade_no')
            out_trade_no = data.get('out_trade_no')

            Payment.objects.create(
                trade_id = trade,
                order = out_trade_no
            )

            # 更新订单状态
            # 5. 更新订单状态
            OrderInfo.objects.filter(order_id=out_trade_no).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])
            return Response({'trade_id': trade})
